#include <stdlib.h>
#include <string.h>

#include "../include/search.h"

int bisearch(void *sorted, const void *target, int size, int esize, int(*compare)(const void *key1, const void *key2))
{
	int left, right, mid;
	left = 0;
	right = size -1;
	int cmp_result;

	while (left <= right)
	{
		mid = (left + right)/2;
		cmp_result = compare(target, (char *)(sorted + mid * esize));

		switch (cmp_result)
		{
			case 1:
				left = mid + 1;
			break;

			case -1:
				right = mid - 1;
			break;

			case 0:
				return mid;
		}
	}

	return -1;
}
